<template>
  <div class="product-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item :label="$t('product.productCode')" prop="productCode">
        <el-input v-model="queryParams.productCode" :placeholder="$t('product.productCode')" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('product.productName')" prop="productName">
        <el-input v-model="queryParams.productName" :placeholder="$t('product.productName')" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('common.search')
          }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.reset') }}</el-button>
        <el-button type="success" icon="el-icon-plus" size="mini" @click="handleAdd">{{ $t('common.add') }}</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="productList" style="width: 100%" border
      :header-cell-style="{ background: '#fafafa', color: '#333' }" :cell-style="{ padding: '12px 0' }">
      <!-- 展开行 -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-image v-for="(item, index) in scope.row.thumbUrl" :key="index"
            style="width: 80px; height: 80px; border-radius: 2px;margin-right: 10px;" :src="item"
            :preview-src-list="[...scope.row.thumbUrl]" fit="cover">
          </el-image>

          <div v-html="scope.row.description"></div>

        </template>
      </el-table-column>

      <!-- <el-table-column prop="productCode" :label="$t('product.productCode')" width="120" align="center">
      </el-table-column> -->

      <!-- type -->
      <el-table-column prop="type" label="分类" width="120" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.type == 1">鑑定済カード</span>
          <span v-else-if="scope.row.type == 2">未開封BOX</span>
          <span v-else-if="scope.row.type == 3">オリパ販売</span>
          <span v-else-if="scope.row.type == 4">人気商品</span>
          <span v-else-if="scope.row.type == 5">预约贩卖</span>

          <span v-else>未知类型</span>
        </template>
      </el-table-column>
      <!-- tags -->
      <el-table-column prop="tags" label="标签" width="220">
        <template slot-scope="scope">
          <el-tag v-for="item in scope.row.tags" :key="item" style="margin-right: 5px;">{{tags.find(t => t.id ==
            item).name}}</el-tag>
        </template>
      </el-table-column>


      <el-table-column prop="productName" :label="$t('product.productName')" min-width="200" align="left"
        show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="price" :label="$t('product.price')" width="100" align="right">
        <template slot-scope="scope">
          <span style="color:#f56c6c">¥{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="postMoney" :label="$t('product.postMoney')" width="100" align="right">
        <template slot-scope="scope">
          <span style="color:#f56c6c">¥{{ scope.row.postMoney }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="stock" :label="$t('product.stock')" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.stock }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="coverUrl" :label="$t('product.coverUrl')" width="100" align="center">
        <template slot-scope="scope">
          <el-image style="width: 80px; height: 80px; border-radius: 2px;" :src="scope.row.coverUrl"
            :preview-src-list="[scope.row.coverUrl, ...scope.row.thumbUrl]" fit="cover">
          </el-image>
        </template>
      </el-table-column>

      <el-table-column :label="$t('common.operation')" width="160" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">{{ $t('common.edit')
            }}</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">{{
            $t('common.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商品对话框 -->
    <el-drawer :title="title" :visible.sync="open" size="700px" append-to-body :wrapper-closable="false"
      custom-class="product-drawer">
      <div class="drawer-container">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="drawer-form">
          <el-form-item label="商品板块" prop="type" class="form-item">
            <el-select v-model="form.type" placeholder="请选择商品板块" class="full-width-input">
              <el-option label="已鉴定卡牌" value="1"></el-option>
              <el-option label="未开封BOX" value="2"></el-option>
              <el-option label="福袋活动" value="3"></el-option>
              <el-option label="人气商品" value="4"></el-option>
              <el-option label="预售卡牌" value="5"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品标签" prop="tags" class="form-item">
            <el-select v-model="form.tags" multiple="" placeholder="请选择商品标签" class="full-width-input">
              <el-option v-for="item in tags" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('product.productName')" prop="productName" class="form-item">
            <el-input v-model="form.productName" :placeholder="$t('product.productName')" class="full-width-input" />
          </el-form-item>

          <div class="form-row">
            <el-form-item :label="$t('product.price')" prop="price" class="form-item half-width">
              <el-input-number v-model="form.price" :precision="2" :step="1" :min="400" class="full-width-input"
               />
            </el-form-item>

            <el-form-item :label="$t('product.postMoney')" prop="postMoney" class="form-item half-width">
              <el-input-number v-model="form.postMoney" :precision="2" :step="1" :min="0" class="full-width-input"
                />
            </el-form-item>
          </div>

          <el-form-item :label="$t('product.stock')" prop="stock" class="form-item">
            <el-input-number v-model="form.stock" :min="0" class="full-width-input"  />
          </el-form-item>

          <el-form-item label="描述" class="form-item">
            <editor v-model="form.description" />
          </el-form-item>

          <el-form-item :label="$t('product.coverUrl')" prop="coverUrl" class="form-item">
            <image-upload1 v-model="form.coverUrl" :limit="1" />
          </el-form-item>

          <el-form-item :label="$t('product.thumbUrl')" prop="thumbUrl" class="form-item">
            <image-upload1 v-model="form.img" />
          </el-form-item>
        </el-form>
      </div>

      <div class="drawer-footer">
        <el-button @click="cancel" size="medium">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="submitForm" size="medium">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listProduct, deleteProduct, addProduct } from '@/api/system/product'
import Pagination from "@/components/Pagination"
import ImageUpload from "@/components/ImageUpload/index"
import ImageUpload1 from "@/components/ImageUpload/index1"
import Editor from "@/components/Editor/index"

export default {
  name: "Product",
  components: { Pagination, ImageUpload1, Editor },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        price: 400,
      },
      // 表单校验
      rules: {
        productCode: [
          { required: true, message: "商品编号不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
        postMoney: [
          { required: true, message: "邮费不能为空", trigger: "blur" }
        ],
        stock: [
          { required: true, message: "库存不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "商品分类不能为空", trigger: "change" }
        ],
        tags: [
          { required: true, message: "商品标签不能为空", trigger: "change" }
        ],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productCode: undefined,
        productName: undefined
      },
      // 上传图片的URL
      uploadUrl: process.env.VUE_APP_BASE_API + "/file/s3/upload",
      tags: [
        {
          id: "1",
          name: 'PSA10'
        },
        {
          id: "2",
          name: 'PSA鉴定'
        },
        {
          id: "3",
          name: '限定'
        },
        {
          id: "4",
          name: 'NEW'
        },
        {
          id: "5",
          name: '折扣'
        },
      ]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t('common.add');
    },
    /** 表单重置 */
    reset() {
      this.form = {
        productCode: undefined,
        productName: undefined,
        price: 400,
        coverUrl: undefined
      };
      this.resetForm("form");
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // let tags = []
      // row.tags.forEach(item => {
      //   let tag = this.tags.find(t => t.id == item)
      //   if (tag) {
      //     tags.push(tag)
      //   }
      // })
      console.log(row.tags);
      this.form = {
        id: row.id,
        productCode: row.productCode,
        productName: row.productName,
        price: row.price,
        postMoney: row.postMoney,
        stock: row.stock,
        coverUrl: row.coverUrl,
        img: row.thumbUrl ? row.thumbUrl.join(',') : '',
        type: row.type,
        description: row.description,
        tags: row.tags,
        // coverUrlList: row.coverUrl.length > 10 ? [row.coverUrl] : []
        // coverUrlList: row.coverUrl
      };
      this.open = true;
      this.title = this.$t('common.edit');
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除商品编号为"' + row.productCode + '"的数据项？').then(() => {
        return deleteProduct(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.img && this.form.img.length > 0) {
            this.form.thumbUrl = this.form.img.split(',') || '';
          }
          if (this.form.coverUrlList && this.form.coverUrlList.length > 0) {
            // this.form.coverUrl = this.form.coverUrlList
          }
          console.log(this.form);
          addProduct(this.form).then(response => {
            this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 上传成功回调 */
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.form.coverUrl = res.data.url;
        this.$modal.msgSuccess("上传成功");
      } else {
        this.$modal.msgError("上传失败");
      }
    },
    /** 上传前校验文件 */
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;


      return isJPG && isLt2M;
    }
  }
};
</script>

<style scoped lang="scss">
.product-drawer {
  .drawer-container {
    height: calc(100vh - 120px);
    padding: 20px;
    overflow-y: auto;

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: #dcdfe6;
      border-radius: 3px;
    }
  }

  .drawer-form {
    .form-item {
      margin-bottom: 22px;

      .el-form-item__label {
        font-weight: 500;
        color: #606266;
      }
    }

    .form-row {
      display: flex;
      gap: 20px;

      .half-width {
        flex: 1;
      }
    }

    .full-width-input {
      width: 100%;
    }

    .upload-container {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      padding: 10px;
      background: #fafafa;

      &:hover {
        border-color: #409EFF;
      }
    }
  }
}

.drawer-footer {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 700px;
  padding: 16px 20px;
  background: #fff;
  border-top: 1px solid #e4e7ed;
  text-align: right;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  z-index: 1;

  .el-button {
    padding: 9px 20px;
    margin-left: 10px;
  }
}

.product-container {
  padding: 20px;
  background: #fff;
}

.el-table {
  margin-top: 15px;
}

.el-button--text {
  padding: 0 5px;
}

.el-button--text:hover {
  color: #409EFF;
}

.el-button--text.el-button--danger:hover {
  color: #f56c6c;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
